package com.ccx.coachsite.service;

import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.ccx.coachsite.CoachSiteMainActivity;
import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.MessageInfo;
import com.ccx.coachsite.ui.own.OwerProvider;

public class SystemMessageTask extends AsyncTask<Integer, Integer, Boolean> {

	private Context context;
	private List<MessageInfo> messages;

	public SystemMessageTask(Context context) {
		this.context = context;
	}

	@Override
	protected Boolean doInBackground(Integer... params) {
		messages = OwerProvider.getInstance().getMessageList(context);
		if (messages != null && messages.size() > 0)
			return true;
		return false;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		if (result) {
			NotificationManager nManager = (NotificationManager) context
					.getSystemService(Service.NOTIFICATION_SERVICE);
			for (MessageInfo message : messages) {
				if(message.getIsReaded() == 0)
					sendNotification(nManager, message);
			}
		}
	}

	private void sendNotification(NotificationManager nManager,
			MessageInfo message) {

		Notification notif = new Notification(R.drawable.icon, "您收到新的系统消息",
				System.currentTimeMillis());
		int tmpID = 200000;
		Intent mIntent = new Intent();
		mIntent.setClass(context, CoachSiteMainActivity.class);
		mIntent.putExtra("noSystemMessage", message);

		PendingIntent pIntent = PendingIntent.getActivity(context, tmpID
				+ message.getId(), mIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		notif.flags = Notification.FLAG_AUTO_CANCEL;
		notif.setLatestEventInfo(context,
				"您收到新的系统消息",
				message.getTitle(), pIntent);
		nManager.notify(
				R.string.main_bottom_app_name + tmpID
						+ message.getId(), notif);
	}
}